// src/directives/loadmore.ts
import { Directive, DirectiveBinding } from 'vue';
import { debounce, throttle } from '@/utils/yuUtils.js';

export const loadmore: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
    const selectWrap: any = el.querySelector('.scrollTable .el-table__body-wrapper .el-scrollbar__wrap') as HTMLElement;
    console.log('🚀 ~ mounted ~ selectWrap:', selectWrap);

    const debouncedScrollHandler = debounce(() => {
      const scrollDistance = selectWrap.scrollHeight - selectWrap.scrollTop - selectWrap.clientHeight;
      const instance = binding.instance;
      console.log('🚀 ~ debouncedScrollHandler ~ instance:', binding);

      const page = instance?.$data.tableRequestParams.page;

      const toploadMorePage = instance?.$data.toploadMorePage;
      // const isTableTopMoreText = instance?.$data.isTableTopMoreText;

      if (selectWrap.scrollTop <= 0 && toploadMorePage !== 0) {
        if (instance) {
          instance.$data.isTableTopMoreText = true;
        }
      } else {
        if (instance) {
          instance.$data.isTableTopMoreText = false;
        }
      }

      if (page > 0 && scrollDistance <= 0.9) {
        binding.value(page); // 执行在使用时绑定的函数
      }
    }, 300); // 调整延迟时间以适应你的需求

    // 保存监听器引用
    selectWrap._scrollHandler = debouncedScrollHandler;
    selectWrap.addEventListener('scroll', selectWrap._scrollHandler);
  }
};
